<template>
  <div class="my-orders-container">
    <div class="header-panel">
      <h2>我的订单</h2>
      <button @click="router.push('/booking')" class="booking-btn">前往预订</button>
    </div>

    <div v-if="orders.length === 0">暂无订单</div>

    <div class="orders-container">
      <div class="order-item" v-for="order in orders" :key="order.id">
        <h3>订单号：{{ order.id }}</h3>
        <p>会议室：{{ order.room_name }}</p>
        <p>使用时间：{{ formatTime(order.start_time) }} 至 {{ formatTime(order.end_time) }}</p>
        <p>订单状态：<span :class="`status-tag ${order.order_status}`">{{ order.order_status }}</span></p>

        <!-- 锁定状态显示倒计时和支付按钮 -->
        <div v-if="isLocked(order)" class="payment-timer">
          <p>请在 {{ getOrderCountdown(order) }} 内完成支付</p>
          <button @click="goToPayment(order)">去支付</button>
        </div>

        <p v-else-if="canCancel(order)">
          <button @click="handleCancel(order)">取消预订</button>
        </p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import axios from '../axios';
import { useAutoRefresh } from '../utils/useAutoRefresh';
import { useUserStore } from '../store/UserStore';
import { useRouter } from 'vue-router'
import { useWebSocketStore } from '../store/WebSocketStore';

const router = useRouter();
const orders = ref([]);
const userStore = useUserStore();

const countdowns = ref({}); // 存储每个订单的倒计时字符串

const isLocked = (order) => {
  return order.order_status === '锁定';
};

// 启动全局倒计时定时器
let countdownInterval = null;

const startGlobalCountdown = () => {
  if (countdownInterval) clearInterval(countdownInterval);

  countdownInterval = setInterval(() => {
    const now = new Date();
    const updated = { ...countdowns.value };

    try {
      orders.value.forEach(order => {
        if (order.order_status !== '锁定') return;

        const createdTime = new Date(order.create_time);
        const expireTime = new Date(createdTime.getTime() + 30 * 60 * 1000); // 创建时间+30分钟
        const remaining = Math.max(0, Math.floor((expireTime - now) / 1000));

        const minutes = String(Math.floor(remaining / 60)).padStart(2, '0');
        const seconds = String(remaining % 60).padStart(2, '0');

        updated[order.id] = `${minutes}:${seconds}`;

        // 增加空值保护和状态判断
        const currentDisplay = countdowns.value[order.id] || '00:00';

        if (remaining <= 0 && currentDisplay !== "00:00") {
          updated[order.id] = "00:00"; // 防止重复触发
          // alert(`订单 ${order.id} 已超时`);
          autoCancelOrder(order);
        }
      });

      countdowns.value = updated;
    } catch (error) {
      console.error('倒计时更新失败:', error);
    }
  }, 1000);
};

const autoCancelOrder = async (order) => {
  try {
    alert(`订单 ${order.id} 已超时，系统将自动取消该订单`);

    // 本地更新状态
    orders.value = orders.value.map(o =>
      o.id === order.id ? { ...o, order_status: '已取消' } : o
    );

    // 向后端发送请求标记为已取消
    await axios.post(`/orders/${order.id}/cancel`);

  } catch (error) {
    console.error('自动取消订单失败:', error);
  }
};

const getOrderCountdown = (order) => {
  return countdowns.value[order.id] || '00:00';
};

onMounted(async () => {
  try {
    const response = await axios.get('/orders/my');
    orders.value = response.data.data;
    // 启动倒计时更新
    startGlobalCountdown();

  } catch (error) {
    alert('获取订单列表失败');
  }
});

onMounted(() => {
  // startGlobalCountdown();
  useAutoRefresh(async () => {
    const response = await axios.get('/orders/my');
    orders.value = response.data.data;
  }, 2000);
});

// 更新订单状态
const updateOrderStatus = (orderId, status) => {
  orders.value = orders.value.map(o =>
    o.id === orderId ? { ...o, order_status: status } : o
  );
};

// 处理订单更新事件
const handleOrderUpdated = (payload) => {
  updateOrderStatus(payload.orderId, payload.status);
};

onMounted(() => {
  const wsStore = useWebSocketStore();
  wsStore.on('server:order-updated', handleOrderUpdated);
});

onUnmounted(() => {
  const wsStore = useWebSocketStore();
  wsStore.off('server:order-updated', handleOrderUpdated);
});

onUnmounted(() => {
  if (countdownInterval) {
    clearInterval(countdownInterval);
  }
});

// 去支付
const goToPayment = (order) => {
  router.push({
    path: '/confirm',
    query: {
      roomId: order.room_id,
      startTime: order.start_time,
      endTime: order.end_time,
      participantNum: order.participant_num,
      orderId: order.id
    }
  });
};

// 判断订单是否可取消
const canCancel = (order) => {
  return order.order_status === '预定';
};

// 提交取消订单请求
const handleCancel = async (order) => {
  const now = new Date();
  const startTime = new Date(order.start_time);
  const timeDiff = startTime - now;
  const hoursBefore = Math.floor(timeDiff / (1000 * 60 * 60));

  // 时间判断
  if (hoursBefore < 24) {
    alert('距离会议开始不足24小时，无法申请取消预订');
    return;
  }

  // 计算退款比例
  let refundRateText = '';
  if (hoursBefore >= 72) {
    refundRateText = '提前 72 小时退全款';
  } else if (hoursBefore >= 48) {
    refundRateText = '提前 48 小时退 75%';
  } else if (hoursBefore >= 24) {
    refundRateText = '提前 24 小时退 25%';
  }

  // 显示提示框
  const confirmMessage = `您距离会议开始还有 ${hoursBefore} 小时。\n\n退款规则：\n${refundRateText}\n\n是否确认取消预订？`;
  if (!confirm(confirmMessage)) return;

  // 提交取消申请
  try {
    const response = await axios.post(`/cancel/${order.id}`);
    alert('取消申请已提交，等待审核');

    // 标记为取消申请待审核状态
    orders.value = orders.value.map(o =>
      o.id === order.id ? { ...o, cancel_request_status: '待审核' } : o
    );

  } catch (error) {
    const errorMessage = error.response?.data?.message || '取消失败，请重试';
    alert(errorMessage);
  }
};

// 时间格式化
const formatTime = (time) => {
  if (!time) return '';

  const date = new Date(time);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}`;
};
</script>

<style scoped>
.orders-container {
  max-width: 1000px;
  margin: 0 auto;
  display: flex;
  flex-wrap: wrap; /* 自动换行 */
  gap: 20px; /* 卡片之间留白 */
}

.order-item {
  width: calc(33.33% - 13.33px);
  padding: 15px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  box-sizing: border-box;
  background-color: #fff;
  transition: box-shadow 0.2s ease;
}

.order-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

button {
  color: #e53e3e;
  background: none;
  border: 1px solid #e53e3e;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
}

.header-panel {
  position: relative;
  width: 100%;
  max-width: 900px;
  margin: 0 auto;
  text-align: center;
}
.booking-btn {
  position: absolute;
  right: 0;
  top: 0;
  background-color: #6b7280;
  color: white;
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.booking-btn:hover {
  background-color: #4b5563;
}

.payment-timer {
  color: #e53e3e;
  margin-top: 10px;
}
.payment-timer p {
  font-weight: bold;
}
.payment-timer button {
  margin-top: 5px;
  background-color: #e53e3e;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
}
.payment-timer button:hover {
  background-color: #c22f2f;
}
</style>